import { apiCheckExchangeById, apiExchangeGoods } from "@/apis/jifen";
import { ResponseCodeEnum } from "../constants";
import Taro from "@tarojs/taro";

export const useExchangeGood = () => {
  const exchangeGood = async (id: number, callback?: () => void) => {
    try {
      // 检查是否可兑换
      const checkRes: any = await apiCheckExchangeById(id);
      if (checkRes.code !== ResponseCodeEnum.SUCCESS) {
        Taro.showToast({ title: checkRes.message, icon: "error" });
      }
      const { canExchange } = checkRes.data;
      if (!canExchange) {
        Taro.showToast({ title: "积分不足", icon: "error" });
        return;
      }

      const exchangeRes: any = await apiExchangeGoods(id);
      if (exchangeRes.code !== ResponseCodeEnum.SUCCESS) {
        Taro.showToast({ title: "兑换失败", icon: "error" });
        return;
      }
      Taro.showToast({ title: "兑换成功", icon: "success" });
      if (callback) {
        callback();
      }
    } catch (error) {
      throw new Error(error);
    }
  };

  return { exchangeGood };
};
